package com.dexstudio.currency;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import com.dexstudio.R;
import com.dexstudio.adapters.CurrencyAdapter;
import com.dexstudio.currency.entity.Currency;
import com.dexstudio.threads.AsyncTaskManager;
import com.dexstudio.threads.OnTaskCompleteListener;
import com.dexstudio.threads.Task;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

public class CurrencyActivity extends Activity implements OnTaskCompleteListener {
	//Main Life Cycle Functions
	@Override
	public void onCreate(Bundle instanceState) {
		super.onCreate(instanceState);
		setContentView(R.layout.currency_list);
		
		currencyList = (ListView) findViewById(R.id.currencyList);
		currencyAdapter = new CurrencyAdapter(this.getApplicationContext(), 
				new ArrayList<HashMap<String, String>>(), R.layout.currency_list_row,
				new int[] {R.id.tvCurrencyName, R.id.tvCurrencyBuyValue, R.id.tvCurrencySaleValue});
		currencyList.setAdapter(currencyAdapter);
		
		// Create manager and set this activity as context and listener
		mAsyncTaskManager = new AsyncTaskManager(this, this);
		// Handle task that can be retained before
		mAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
	}
	
	@Override
	public void onStart() {
		super.onStart();
		mAsyncTaskManager.setupTask(new Task(getResources()));
	}
	
	//--Thread Events
	@Override
    public Object onRetainNonConfigurationInstance() {
		// Delegate task retain to manager
		return mAsyncTaskManager.retainTask();
    }
	
	//--
	public void onTaskComplete(Task task) {
		if (task.isCancelled()) {
		    // Report about cancel
		    Toast.makeText(this, R.string.taskCancelled, Toast.LENGTH_SHORT).show();
		} else {
		    LinkedList<Currency> listOfCurrencies = task.getCurrencyList();
		    if (currencyList != null) {
		    	for(int i=0; i<listOfCurrencies.size(); i++) {
		    		Currency currency = listOfCurrencies.get(i);
		    		currencyAdapter.add(currency.getCcy(),
		    				currency.getBuy(),
		    				currency.getSale());
		    	}
		    }
		}
    }
	
	//Objects & Variables
	private ListView currencyList = null;
	private CurrencyAdapter currencyAdapter = null;
	private AsyncTaskManager mAsyncTaskManager;
}
